package com.itlong.cloud.sdkv3.service.impl;

import com.itlong.cloud.POJO.DTO.sdk.v3.ElevatorCheckDTO;
import com.itlong.cloud.POJO.DTO.sdk.v3.OpenDoorCheckDTO;
import com.itlong.cloud.POJO.PO.DeviceElevatorFloorConfigPO;
import com.itlong.cloud.POJO.VO.SDKMessageV3;
import com.itlong.cloud.POJO.VO.common.ProjectIotInfo;
import com.itlong.cloud.app.dao.IAppDeviceDao;
import com.itlong.cloud.app.service.IAppDeviceService;
import com.itlong.cloud.constants.IotConstant;
import com.itlong.cloud.constants.RobotDevelopDeviceTypeConstant;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.SDKV3ErrorCodeEnum;
import com.itlong.cloud.property.dao.IDeviceCloudControllerDao;
import com.itlong.cloud.sdk.dao.ICloudElevatorSDKRobotDao;
import com.itlong.cloud.sdk.service.ICloudElevatorSDKServerCloudService;
import com.itlong.cloud.sdkv3.service.ISDKV3Service;
import com.itlong.cloud.utils.tool.DeviceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SDKV3ServiceImpl implements ISDKV3Service {

    private static final Logger LOG = LoggerFactory.getLogger(SDKV3ServiceImpl.class);

    @Autowired
    IAppDeviceDao iAppDeviceDao;

    @Autowired
    IAppDeviceService iAppDeviceService;

    @Autowired
    ICloudElevatorSDKServerCloudService iCloudElevatorSDKServerCloudService;

    @Autowired
    IDeviceCloudControllerDao iDeviceCloudControllerDao;

    @Autowired
    private ICloudElevatorSDKRobotDao iCloudElevatorSDKRobotDao;

    @Override
    public SDKMessageV3 cloudElevatorCheck(ElevatorCheckDTO dto) {
        String requestId = dto.getRequestId();
        String robotId = dto.getRobotId();
        String deviceUnique = dto.getDeviceUnique();
        String startingLogicalFloor = dto.getStartingLogicalFloor();
        String gotoLogicalFloor = dto.getGotoLogicalFloor();
        String startingNumFloor = dto.getStartingNumFloor();
        String gotoNumFloor = dto.getGotoNumFloor();
        String fromNaturalFloor = dto.getFromNaturalFloor();
        String toNaturalFloor = dto.getToNaturalFloor();
        String userId = dto.getUserId();
        //
        HashMap<String, String> result = new HashMap<>();
        //
        try {
            String projectId = DeviceUtil.getProjectIdByDeviceUnique(deviceUnique);
            int deviceType = DeviceUtil.getDeviceTypeByDeviceUnique(deviceUnique);
            boolean isYQK = DeviceUtil.isYQK(deviceUnique);
            ProjectIotInfo projectIotInfo = iAppDeviceDao.getProjectIotInfoByProjectId(projectId, deviceUnique, deviceType);
            if (projectIotInfo == null) {
                return new SDKMessageV3(SDKV3ErrorCodeEnum.PROJECT_NOT_EXIST.getErrorCode(), requestId);
            }
            if (projectIotInfo.getIotFlag() != IotConstant.IOT_FLAG_HW) {
                return new SDKMessageV3(SDKV3ErrorCodeEnum.IOT_ERROR.getErrorCode(), requestId);
            }
            result.put("deviceId", projectIotInfo.getHuaweiIotId());
            String deviceUniqueList = "";
            String deviceUniqueForFind = deviceUnique;
            //如果是云群控
            if (isYQK) {
                deviceUniqueList = iCloudElevatorSDKServerCloudService.getDeviceUniqueByControllerDeviceUnique(deviceUnique);
                String[] temp = deviceUniqueList.split(",");
                deviceUniqueForFind = temp[0];
                //需要传一个云电梯进去
                Map<String, Object> controller = iAppDeviceDao.getControllerDeviceUnique(deviceUniqueForFind);
                if (controller == null || controller.size() == 0) {
                    return new SDKMessageV3(SDKV3ErrorCodeEnum.YQK_NOT_EXIST.getErrorCode(), requestId);
                }
                if (controller.get("upFloor") == null || controller.get("downFloor") == null) {
                    return new SDKMessageV3(SDKV3ErrorCodeEnum.YQK_FLOOR_NOT_EXIST.getErrorCode(), requestId);
                }
                String upFloor = controller.get("upFloor").toString();
                String downFloor = controller.get("downFloor").toString();
                if (upFloor.equals("") || downFloor.equals("")) {
                    return new SDKMessageV3(SDKV3ErrorCodeEnum.YQK_FLOOR_NOT_EXIST.getErrorCode(), requestId);
                }
                String flag = ">";
                if (Integer.parseInt(startingNumFloor) <= Integer.parseInt(gotoNumFloor)) {
                    flag = "<=";
                }
                if (!checkYQKFloor(fromNaturalFloor, toNaturalFloor, upFloor, downFloor, flag)) {
                    return new SDKMessageV3(SDKV3ErrorCodeEnum.YQK_FLOOR_NOT_EXIST.getErrorCode(), requestId);
                }
                if (controller.get("huaweiIotId") != null) {
                    result.put("deviceId", controller.get("huaweiIotId").toString());
                }
            } else {
                //绑定了群控器的设备只能操作群控器
                String[] in = new String[1];
                in[0] = deviceUnique;
                Map<String, Object> map = iAppDeviceDao.getControllerDeviceUniqueByElevatorDeviceUniques(deviceUnique, in);
                if (map != null && map.size() > 0) {
                    return new SDKMessageV3(SDKV3ErrorCodeEnum.HAS_BIND_YQK_ERROR.getErrorCode(), requestId);
                }
                //检查设备权限
                Map<String, Object> searchDevice = new HashMap<>();
                searchDevice.put("appId", userId);
                searchDevice.put("projectId", projectId);
                searchDevice.put("robotId", robotId);
                searchDevice.put("deviceType", RobotDevelopDeviceTypeConstant.YDT);
                List<String> list = iCloudElevatorSDKRobotDao.getRobotDevelopElevatorKey(searchDevice);
                LOG.info("【cloudElevatorCheck】{} {} {}", searchDevice, list, deviceUnique);
                if (list == null || !list.contains(deviceUnique)) {
                    return new SDKMessageV3(SDKV3ErrorCodeEnum.DEVICE_AUTH_ERROR.getErrorCode(), requestId);
                }
            }
            //传的楼层是否超出范围
            HashMap<String, String> map = new HashMap<>();
            List<DeviceElevatorFloorConfigPO> list = iDeviceCloudControllerDao.getFloorConfigByDeviceUnique(deviceUniqueForFind);
            for (DeviceElevatorFloorConfigPO item : list) {
                map.put(item.getLogicalFloor(), "1");
            }
            if (!map.containsKey(startingLogicalFloor)) {
                return new SDKMessageV3(SDKV3ErrorCodeEnum.FROM_FLOOR_ERROR.getErrorCode(), requestId);
            }
            if (!map.containsKey(gotoLogicalFloor)) {
                return new SDKMessageV3(SDKV3ErrorCodeEnum.TO_FLOOR_ERROR.getErrorCode(), requestId);
            }
            //
            result.put("startingFloor", iAppDeviceDao.getLogicFloorByFloorNum(startingNumFloor, deviceUniqueForFind));
            result.put("gotoFloor", iAppDeviceDao.getLogicFloorByFloorNum(gotoNumFloor, deviceUniqueForFind));
            if (iAppDeviceService.appUserIsVip(userId, projectId)) {
                result.put("isVip", "1");
            }
            return new SDKMessageV3(BaseErrorCodeEnum.SUCCESS.getErrorCode(), requestId, result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new SDKMessageV3(BaseErrorCodeEnum.ERROR.getErrorCode(), requestId);
    }

    @Override
    public SDKMessageV3 openDoorCheck(OpenDoorCheckDTO dto) {
        String requestId = dto.getRequestId();
        String robotId = dto.getRobotId();
        String deviceUnique = dto.getDeviceUnique();
        //
        HashMap<String, String> result = new HashMap<>();
        //
        try {
            String projectId = DeviceUtil.getProjectIdByDeviceUnique(deviceUnique);
            int deviceType = DeviceUtil.getDeviceTypeByDeviceUnique(deviceUnique);
            ProjectIotInfo projectIotInfo = iAppDeviceDao.getProjectIotInfoByProjectId(projectId, deviceUnique, deviceType);
            if (projectIotInfo == null) {
                return new SDKMessageV3(SDKV3ErrorCodeEnum.PROJECT_NOT_EXIST.getErrorCode(), requestId);
            }
            result.put("deviceId", projectIotInfo.getHuaweiIotId());
            //检查设备权限
            Map<String, Object> searchDevice = new HashMap<>();
            searchDevice.put("appId", dto.getUserId());
            searchDevice.put("projectId", projectId);
            searchDevice.put("robotId", robotId);
            searchDevice.put("deviceType", dto.getFlag());
            List<String> list = iCloudElevatorSDKRobotDao.getRobotDevelopElevatorKey(searchDevice);
            LOG.info("【openDoorCheck】{} {} {}", searchDevice, list, deviceUnique);
            if (list == null || !list.contains(deviceUnique)) {
                return new SDKMessageV3(SDKV3ErrorCodeEnum.DEVICE_AUTH_ERROR.getErrorCode(), requestId);
            }
            return new SDKMessageV3(BaseErrorCodeEnum.SUCCESS.getErrorCode(), requestId, result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new SDKMessageV3(BaseErrorCodeEnum.ERROR.getErrorCode(), requestId);
    }

    /**
     * 检查云群控场景下乘梯的起始楼层都安装了外呼设备
     *
     * @return boolean
     */
    public boolean checkYQKFloor(String fromNaturalFloor, String toNaturalFloor, String upFloor, String downFloor, String flag) {
        boolean b1;
        boolean b2;
        //出发楼层 <= 目的楼层
        if (flag.equals("<=")) {
            b1 = contain(upFloor, fromNaturalFloor);
            b2 = contain(downFloor, toNaturalFloor);
        }
        //出发楼层 > 目的楼层
        else {
            b1 = contain(downFloor, fromNaturalFloor);
            b2 = contain(upFloor, toNaturalFloor);
        }
        return b1 && b2;
    }

    /**
     * 字符串是否包含某个值
     *
     * @return boolean
     */
    private boolean contain(String data, String value) {
        String[] list = data.split(",");
        for (String item : list) {
            if (item.equals(value)) {
                return true;
            }
        }
        return false;
    }

}